package com.toKnow.filter;

import com.toKnow.utils.JwtUserSessionUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 拦截/user开头的请求，检查session
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws IOException {
        if(request.getMethod().equals("OPTIONS")) return true;
        HttpSession session = request.getSession();
        boolean loginSuccess = false;
        if(session != null){
            String userToken = (String) session.getAttribute("userToken");
            loginSuccess =  JwtUserSessionUtil.verify(userToken);
        }
        if(!loginSuccess){
            System.out.println("login interceptor fail");
            response.sendRedirect(request.getContextPath() + "/"); //验证失败则返回首页
        } else {
            System.out.println("login interceptor success");
        }
        return loginSuccess;
    }
}
